package com.csun.cmny.provider.config;

import com.csun.cmny.provider.device.yingshi.YingShiUtils;
import com.csun.cmny.provider.device.yingshi.entity.YingShiAccessTokenVo;
import com.csun.cmny.provider.model.domain.DmcYingShiConfig;
import com.csun.cmny.provider.service.DmcYingShiConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2021/10/12 18:00
 * @Description: TODO
 */
@Slf4j
@Component
@Order(value = 10)
public class YingShiInitRunner implements CommandLineRunner {

    @Resource
    private DmcYingShiConfigService dmcYingShiConfigService;
    @Resource
    private YingShiUtils yingShiUtils;

    /**
     * 存储萤石云应用信息 groupId, DmcYingShiConfig
     */
    public static ConcurrentHashMap<Long, DmcYingShiConfig> ACCESS_TOKEN_MAP = new ConcurrentHashMap<>();

    @Override
    public void run(String... args) throws Exception {
        List<DmcYingShiConfig> dmcYingShiConfigList = dmcYingShiConfigService.selectAll();
        Date now = new Date();
        for (DmcYingShiConfig config : dmcYingShiConfigList) {
            DmcYingShiConfig record = ACCESS_TOKEN_MAP.get(config.getAppKey());
            if (config.getExpireTime().before(now)) { // access token失效了
                YingShiAccessTokenVo yingShiAccessTokenVo = yingShiUtils.getAccessToken(config.getAppKey(), config.getSecret());
                config.setAccessToken(yingShiAccessTokenVo.getAccessToken());
                config.setExpireTime(new Date(yingShiAccessTokenVo.getExpireTime()));
                dmcYingShiConfigService.updateAccessToken(config);
            }
            ACCESS_TOKEN_MAP.put(config.getGroupId(), config);
        }
    }
}
